package org.qpcr.community.project.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hswebframework.web.crud.service.GenericReactiveCrudService;
import org.qpcr.community.project.model.entity.DataAnalysisInterpretationConditionEntity;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Collection;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class DataAnalysisInterpretationConditionService extends GenericReactiveCrudService<DataAnalysisInterpretationConditionEntity, String> {
    public Mono<List<DataAnalysisInterpretationConditionEntity>> listByGroupId(String groupId) {
        return createQuery()
            .where(DataAnalysisInterpretationConditionEntity::getGroupId, groupId)
            .fetch()
            .collectList();
    }

    public Mono<Integer> saveBatch(Collection<DataAnalysisInterpretationConditionEntity> entities) {
        if (entities == null || entities.isEmpty()) {
            return Mono.just(0);
        }

        String groupId = entities.stream().findFirst().get().getGroupId();

        // 先删除旧数据，然后插入新数据
        return deleteByGroupId(groupId)
            .then(Flux.fromIterable(entities).as(super::insert));
    }

    public Mono<Integer> deleteByGroupId(String groupId) {
        return createDelete()
            .where(DataAnalysisInterpretationConditionEntity::getGroupId, groupId)
            .execute();
    }
}
